package detect;

import interfaces.Detect;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import entities.CssTechnology;
import entities.Domain;

public class DetectCssSemanticUI implements Detect {
	@SuppressWarnings("serial")
	@Override
	public void getInfo(Map<String, Object> obj) {
		// TODO Auto-generated method stub
		Document doc = (Document) obj.get("doc");
		Domain domain = (Domain) obj.get("domain");
		Type listType = new TypeToken<List<CssTechnology>>() {
		}.getType();
		List<CssTechnology> cssTechnologies = new Gson().fromJson(
				domain.getCssTechnology(), listType);

		if (cssTechnologies == null) {
			cssTechnologies = new ArrayList<CssTechnology>();
		}

		try {
			CssTechnology cssTechnology = new CssTechnology();

			Elements listCss = doc.select("link");
			String cssName = "";
			String cssVersion = "";
			for (Element css : listCss) {
				String href = css.attr("href");

				if (!href.isEmpty() && href.toLowerCase().contains("semantic")) {
					cssName = "Semantic UI";
					String name = href.replaceAll("[^/]*[/]+", "").replaceAll(
							"[?]+[^?]*", "");
					Pattern p = Pattern.compile("([0-9]+[.]{1})+[0-9]{1}");
					Matcher m = p.matcher(name); // get a matcher object
					while (m.find()) {
						cssVersion = name.substring(m.start(), m.end());
						break;
					}

					if (cssVersion.isEmpty()) {
						m = p.matcher(href); // get a matcher object
						while (m.find()) {
							cssVersion = href.substring(m.start(), m.end());
							break;
						}
					}
				}
			}

			if (cssName.isEmpty()) {
				Elements listJs = doc.select("script");
				for (Element js : listJs) {
					String src = js.attr("src");
					if (!src.isEmpty()
							&& src.toLowerCase().contains("semantic")) {
						cssName = "Semantic UI";
						String name = src.replaceAll("[^/]*[/]+", "")
								.replaceAll("[?]+[^?]*", "");

						Pattern p = Pattern.compile("([0-9]+[.]{1})+[0-9]{1}");
						Matcher m = p.matcher(name); // get a matcher object
						while (m.find()) {
							cssVersion = name.substring(m.start(), m.end());
							break;
						}

						if (cssVersion.isEmpty()) {
							m = p.matcher(src); // get a matcher object
							while (m.find()) {
								cssVersion = src.substring(m.start(), m.end());
								break;
							}
						}
					}
				}
			}

			if (!cssName.isEmpty()) {
				cssTechnology.setN(cssName);
				cssTechnology.setV(cssVersion);

				cssTechnologies.add(cssTechnology);
			}

			domain.setCssTechnology(new Gson().toJson(cssTechnologies));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
